package Tools
{
  import flashx.textLayout.conversion.TextConverter;
  import flashx.textLayout.elements.FlowElement;
  import flashx.textLayout.elements.FlowGroupElement;
  import flashx.textLayout.elements.LinkElement;
  import flashx.textLayout.elements.TextFlow;
  import flashx.textLayout.events.FlowElementMouseEvent;

  /**
   * ...
   * @author Roman Marchenko
   */
  public class HtmlSpecials
  {
    public static function decode(str:String):String
    {
      var regexp:RegExp;
      var res:String = str;

      regexp = new RegExp("&amp;", "g");
      res = res.replace(regexp, "&");
      regexp = new RegExp("&#39;", "g");
      res = res.replace(regexp, "'");
      regexp = new RegExp("&#33;", "g");
      res = res.replace(regexp, "!");

      return res;
    }

    public static function removeAnchors(htmltext:String):String
    {
      var regexp:RegExp = new RegExp("< *a .*?>(.*?)</ *a *>", "gs");
      var res:String = htmltext.replace(regexp, "$1");
      return res;
    }

    public static function replaceEOLs(htmltext:String):String
    {
      var regexp:RegExp = new RegExp("\r\r", "g");
      var res:String = htmltext.replace(regexp, "<p>");

      regexp = new RegExp("\n\n", "g");
      res = res.replace(regexp, "<p>");

      regexp = new RegExp("\r", "g");
      res = res.replace(regexp, "<br>");

      regexp = new RegExp("\n", "g");
      res = res.replace(regexp, "<p>");

      return res;
    }

    /**
     * Iterates through all the
     * elements in the TextFlow until it finds a LinkElement, and adds a
     * FlowElementMouseEvent.CLICK event handler to that Link Element.
     */
    public static function replaceLinkClickHandlers(group:FlowGroupElement, linkClickedHandler:Function):void
    {
      for (var i:int = 0; i < group.numChildren; i++)
      {
        var element:FlowElement = group.getChildAt(i);
        if (element is LinkElement)
        {
          var link:LinkElement = element as LinkElement;
          link.addEventListener(FlowElementMouseEvent.CLICK, linkClickedHandler, false, 0, true);
        }
        else if (element is FlowGroupElement)
        {
          replaceLinkClickHandlers(element as FlowGroupElement, linkClickedHandler);
        }
      }
    }
  }

}